package com.hjy.test;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

//Promise相当于一个容器，可以用于存放各个线程中的结果，然后让其他线程去获取该结果
public class NettyPromise {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup(2);
        EventLoop eventLoop = group.next();
        //创建promise 对象 用于存放结果
        DefaultPromise<Object> promise = new DefaultPromise<>(eventLoop);
        new Thread(()->{
            try{
//                int i = 10/0;
                TimeUnit.SECONDS.sleep(1);
                promise.setSuccess(50);
            }catch (Exception e){
                promise.setFailure(e.getCause());
                e.printStackTrace();
            }
        }).start();

        // 主线程从Promise中获取结果
        System.out.println(Thread.currentThread().getName() + "" + promise.get());
        System.out.println("end");
    }
}
